import React from 'react';
export default class Uploader extends React.Component {

    handleClick() {
        if (wx) {
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: (res)=> {
                    let ids = res.localIds;
                    ids.length > 0 && this.onSelected(ids[0]);
                }
            });
        }
    }

    onSelected(localId) {
        wx.uploadImage({
            localId, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: (res)=> {
                var serverId = res.serverId;
                $.get('/api/default/upload', {
                    id: serverId
                }, (data)=> {
                    this.props.onUploaded(data.url);
                }, 'json');
            }
        });
    }

    render() {
        return (
            <div className="uploader">
                <span className="tips">{this.props.btnText}</span>
                <div className="btn" onClick={e=>this.handleClick()}>选择图片</div>
            </div>
        )
    }
}

Uploader.propTypes = {
    onUploaded: React.PropTypes.func.isRequired,
    btnText: React.PropTypes.string.isRequired
};